package com.example.iot;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.github.mikephil.charting.charts.LineChart;

import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class MainActivity extends AppCompatActivity {
    private static final String HOST = "xx.xx.xx.xx";
    private static final int PORT = 8888;
    private final Handler handler = new Handler(Looper.getMainLooper());
    private LineChartManager lineChartManagerTemp;
    private LineChartManager lineChartManagerResp;
    private TextView tempText;
    private TextView respText;
    private Thread socketThread;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (!NetworkStateReceiver.isConnected(this)) {
            Toast.makeText(this, "无网络连接", Toast.LENGTH_SHORT).show();
        }

        NetworkStateReceiver networkStateReceiver = new NetworkStateReceiver();
        networkStateReceiver.setNetworkStateListener(new NetworkStateListener() {
            @Override
            public void onNetworkConnected() {
                Toast.makeText(ContextManager.getContext(), "网络已连接", Toast.LENGTH_SHORT).show();
                startSocketThread();
            }

            @Override
            public void onNetworkDisconnected() {
                Toast.makeText(ContextManager.getContext(), "网络已断开", Toast.LENGTH_SHORT).show();
                lineChartManagerTemp.clear();
                lineChartManagerResp.clear();
            }
        });

        LineChart lineChartTemp = findViewById(R.id.line_chart_temp);
        LineChart lineChartResp = findViewById(R.id.line_chart_resp);
        tempText = findViewById(R.id.temp_text);
        respText = findViewById(R.id.resp_text);

        lineChartManagerTemp = new LineChartManager(lineChartTemp, "Temperature", Color.BLUE);
        lineChartManagerResp = new LineChartManager(lineChartResp, "RES-Photo", Color.BLUE);

        lineChartManagerTemp.getLineDataSet().setDrawCircleHole(true);
        lineChartManagerResp.getLineDataSet().setDrawCircleHole(true);

        lineChartManagerTemp.setYAxis(40.0f, 10.0f, 10);
        lineChartManagerResp.setYAxis(4.0f, 0.0f, 10);

        lineChartManagerTemp.setDescription("温度值曲线");
        lineChartManagerResp.setDescription("光敏电阻值曲线");
    }

    private void startSocketThread() {
        if (socketThread != null && socketThread.isAlive()) {
            socketThread.interrupt();
        }
        socketThread = new Thread(new Runnable() {
            private float bytes2Float(byte[] buffer, @Nullable Integer offset) {
                if (offset == null) {
                    offset = 0;
                }

                ByteBuffer bb = ByteBuffer.wrap(buffer, offset, 4);
                bb.order(ByteOrder.LITTLE_ENDIAN);
                return bb.getFloat();
            }

            @SuppressLint("DefaultLocale")
            @Override
            public void run() {
                try (Socket socket = new Socket(HOST, PORT)) {
                    handler.post(() -> Toast.makeText(ContextManager.getContext(), "Socket connected", Toast.LENGTH_SHORT).show());
                    while (true) {
                        try {
                            byte[] buffer = new byte[10];
                            int bytesRead = socket.getInputStream().read(buffer);

                            if (bytesRead == 10) {
                                if (buffer[0] == (byte) 0xAB && buffer[9] == (byte) 0xEF) {
                                    float temp = this.bytes2Float(buffer, 1);
                                    float resp = this.bytes2Float(buffer, 5);

                                    lineChartManagerTemp.addEntry(temp);
                                    lineChartManagerResp.addEntry(resp);
                                    handler.post(() -> tempText.setText(String.format("Temperature: %.2f°C", temp)));
                                    handler.post(() -> respText.setText(String.format("RES-Photo: %.2fV", resp)));
                                }
                            }
                        } catch (Exception ignored) {

                        }
                    }
                } catch (Exception e) {
                    handler.post(() -> Toast.makeText(ContextManager.getContext(), "Socket exception", Toast.LENGTH_SHORT).show());
                    e.printStackTrace();
                }
            }
        });

        socketThread.start();
    }
}